import {
  orderListApi,
  orderDeleteApi,
  orderCreateApi,
  orderDetailApi,
  setOrderStateApi,
  watchReceiverApi,
  closeWRApi,
  watchListApi
} from 'src/api/order'
import { createOrder } from 'classes/order'

export function getOrderList (router, reload) {
  watchList(reload)
  return orderListApi(router).then((list) => {
    list = list.map(item => createOrder(item))
    return Promise.resolve(list)
  })
}

export function getOrderDetail (id) {
  return orderDetailApi(id)
    .then(data => Promise.resolve(createOrder(data)))
}

export function addOrder (sender, receiver) {
  const data = {
    id: -1,
    senderName: sender.name,
    senderPhone: sender.phone,
    senderAddress: sender.address,
    receiverName: receiver.name,
    receiverPhone: receiver.phone,
    receiverAddress: receiver.address,
    code: -1
  }
  return orderCreateApi(data).then(data => Promise.resolve(data.id))
}

export function deleteOrder (order) {
  return orderDeleteApi(order).then(() => Promise.resolve(order.id))
}

export function setOrderState (order, state) {
  return setOrderStateApi(order, state)
}

export function watchReceiver (orderId) {
  return watchReceiverApi(orderId)
}
export function closeWR (orderId) {
  return closeWRApi(orderId)
}

export function watchList (reload) {
  return watchListApi().then((msg) => {
    msg === 'timeout'
      ? watchList(reload)
      : reload()
  }).catch(() => {})
}
